package br.sceweb.servico;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;

import br.sceweb.dominio.Estagio;
import br.sceweb.dominio.EstagioSupervisionado;

public class HibernateEstagioDAO implements IEstagioDAO {
	Logger logger = Logger.getLogger(HibernateEstagioDAO.class);

	public String cadastra(Estagio e) {

		logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>inicializando o procedimento cadastra");
		String codigoRetorno = "";
		try {
			EntityManagerFactory factory = Persistence.createEntityManagerFactory("sceweb");
			EntityManager em = factory.createEntityManager();
			em.getTransaction().begin();
			em.persist(e);
			em.getTransaction().commit();
			em.close();
			codigoRetorno = "Cadastro realizado com sucesso";
		} catch (PersistenceException exception) { // HibernateException
			codigoRetorno = "Erro no cadastro";
			logger.info("disparou um erro na transacao de persistencia do tipo PersistenceException = "
					+ exception.toString());
		}

		return codigoRetorno;

	}

	public int exclui(String ra) {

		logger.info("inicializando o procedimento");
		int codigoRetorno = 0;
		try {
			EntityManagerFactory factory = Persistence.createEntityManagerFactory("sceweb");
			EntityManager em = factory.createEntityManager();

			String jpql = " DELETE FROM Estagio e WHERE e.Ra = :Ra";
			em.getTransaction().begin();
			Query query = em.createQuery(jpql);
			query.setParameter("Ra", ra);
			codigoRetorno = query.executeUpdate();
			logger.info(" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>resultado da query exclui ra ="+ ra + " e codigoRetorno =" + codigoRetorno + " excluido");
			em.getTransaction().commit();

		} catch (HibernateException exception) {
			exception.printStackTrace();

		}

		return codigoRetorno;

	}

	public Estagio consulta(Estagio e) {
		
		return null;
	}

	@Override
	public List<Estagio> findAll() {
		List<Estagio> lista = new ArrayList<Estagio>();
		try {
			EntityManagerFactory factory = Persistence.createEntityManagerFactory("sceweb");
			EntityManager em = factory.createEntityManager();
			em.getTransaction().begin();
			Query query = em.createQuery("SELECT e from Estagio e");
			lista = query.getResultList();

		} catch (Throwable e) {
		}
		return lista;
	}

	@Override
	public void remove(Estagio estagio) {
		// TODO Auto-generated method stub

	}

	@Override
	public ArrayList<Estagio> consulta(String Ra) {

		List<Estagio> results = null;
		try {
			EntityManagerFactory factory = Persistence.createEntityManagerFactory("sceweb");
			EntityManager em = factory.createEntityManager();
			String hql = " SELECT e FROM Estagio e WHERE e.Ra = :Ra";
			em.getTransaction().begin();
			Query query = em.createQuery(hql);
			query.setParameter("Ra", Ra);
			results = query.getResultList();
			em.getTransaction().commit();

		} catch (HibernateException exception) {
			// throw new Exception("ERRO..... " );
			logger.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> excecao no consulta="	+ exception.getMessage());

		}
		return (ArrayList<Estagio>) results;
	}

	@Override
	public String alterar(Estagio e) {		
		String codigoRetorno = "";	
		try {EntityManagerFactory factory = Persistence.createEntityManagerFactory("sceweb");
			EntityManager em = factory.createEntityManager();

			em.getTransaction().begin();

			Query query = em.createQuery("UPDATE Estagio c SET c.Ra = :ra, c.Nome_Completo = :nome, c.dataInicio =:inicio, c.dataTermino =: termino,"
					+ " c.empresa =: empresa, c.responsavel =: responsavel, c.curso =: curso WHERE c.Ra = :ra");
			query.setParameter("nome", e.getRa());
			query.setParameter("nome", e.getNome_Completo());
			query.setParameter("inicio", e.getDataInicio());
			query.setParameter("termino", e.getDataTermino());
			query.setParameter("empresa", e.getEmpresa());
			query.setParameter("responsavel", e.getResponsavel());
			query.setParameter("curso", e.getCurso());	
			
			query.executeUpdate();
			logger.info(" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>resultado da query alterado");
			em.getTransaction().commit();

			em.close();
			factory.close();
		    }catch (PersistenceException exception ) {
		    	codigoRetorno = "Erro no cadastro";
				logger.info("disparou um erro na transacao de persistencia do tipo PersistenceException = "
						+ exception.toString());
			}
			return codigoRetorno;
	}

}
